
<template>
<div class="add-project">
  <el-dialog class="add-project-dialog" :title="editProjectId!==null?'修改项目信息':'登记项目信息'" :visible.sync='editProjectSync' :before-close="handleCloseDialog" width="65%">
    <el-card class="add-project-card" shadow="never" v-loading="loading">
      <div class="add-project__messageForm">
        <el-form class="add-project-form" :model="projectMessage" :inline="true" ref="addProjectForm"  :rules="addProjectRules" label-width="100px">
            <el-form-item label="项目名称：" prop="projectName">
              <el-input  class="add-message" v-model="projectMessage.projectName" placeholder="请输入项目名称" clearable/>
            </el-form-item>
          <el-form-item label="项目类型：" prop="projectType">
            <el-input class="add-message" v-model="projectMessage.projectType" placeholder="请输入项目类型" clearable/>
          </el-form-item>
          <el-form-item label="详细地址：" prop="projectLocation">
            <el-input class="add-message" v-model="projectMessage.projectLocation" placeholder="请输入地址" clearable/>
          </el-form-item>
          <el-form-item label="联系方式：" prop="projectContact">
            <el-input class="add-message" v-model="projectMessage.projectContact" placeholder="请输入联系方式" clearable/>
          </el-form-item>
          <el-form-item label="评审人数：" prop="projectReviewNumber">
            <el-input-number class="add-message" v-model="projectMessage.projectReviewNumber" :precision="0" :step="1"  step-strictly :min="1" :max="10"/>
          </el-form-item>
          <el-form-item label="评审时间：" prop="projectReviewTime">
            <el-date-picker  class="add-message" v-model="projectMessage.projectReviewTime" type="datetime" placeholder="选择日期时间"
                             value-format="yyyy-MM-dd HH:mm:ss"  :picker-options="startPickerOptions"/>
          </el-form-item>
        </el-form>
      </div>
      <VueEditor maxLength="2000" placeholder="请输入项目简介..." class="add-project-editor"
                 v-model="projectMessage.projectContent" :editorToolbar="customToolbar"/>
      <div class="add-project-button">
        <el-button @click="handleCloseDialog">取 消</el-button>
        <el-button type="primary" v-show="!editProjectId" @click="handleAddProject">确认添加</el-button>
        <el-button type="primary" v-show="editProjectId!==null" @click="handleEditProject">确认修改</el-button>
      </div>
    </el-card>
  </el-dialog>
</div>
</template>
<script>
import { mapState } from 'vuex'
import store from '@/store'
import { Quill, VueEditor } from 'vue2-editor'
import { AddProjectApi, GetProjectById, UpdateProjectApi } from '@/request/project/project-api'
let fontList = ['SimSun','宋体','楷体','黑体','幼圆']
Quill.imports['formats/font'].whitelist = fontList
Quill.register(Quill.imports['formats/font'])
let fontSizeList = [false, '10px','12px','14px','16px','20px','24px']
Quill.imports['attributors/style/size'].whitelist = fontSizeList
Quill.register(Quill.imports['attributors/style/size'])
export default {
  computed:{
    listenEditProjectId(){
      return store.state.ProjectEdit.editProjectId
    },
    ...mapState({
      editProjectSync:state => state.ProjectEdit.editProjectSync,
      editProjectId:state => state.ProjectEdit.editProjectId
    })
  },
  data(){
    return{
      loading:false,
      customToolbar: [
        [{ size: fontSizeList }],
        [{ font: fontList }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }], //几级标题
        ['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
        ['blockquote', 'code-block'], //引用，代码块
        [{ 'list': 'ordered' }, { 'list': 'bullet' }], //列表
        [{ 'script': 'sub' }, { 'script': 'super' }], // 上下标
        [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
        [{ 'direction': 'rtl' }], // 文本方向
        [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
        // [{'font': []}], //字体
        [{ 'align': [] }], //对齐方式
        ['clean'], //清除字体样式
        // ['image', 'video'] //上传图片、上传视频
      ],
      projectMessage:{},
      startPickerOptions:{
        disabledDate:(time)=>{
          return time.getTime()<Date.now()+7*24*3600000
        }
      },
      addProjectRules: {
        projectName:{required:true,message:"请输入项目名",trigger:'blur'},
        projectType:{required:true,message:"请输入项目类型",trigger:'blur'},
        projectLocation:{required:true,message:"请输入项目地址",trigger:'blur'},
        projectContact:{required:true,message:"请输入联系方式",trigger:'blur'},
        projectReviewNumber:{required:true,message:"请输入项目评审人数",trigger:'blur'},
        projectReviewTime:{required:true,message:"请选择项目评审时间",trigger:'blur'}
      }
    }
  },
  methods:{
    //初始化内容
    async init (id) {
      this.loading=true
      let res = await GetProjectById(id)
      if (res&&res.code){
        if (res.data.projectStatus>2){
          this.$message.warning("项目无法修改")
        }else {
          this.projectMessage=res.data
          this.loading=false
        }
      }else {
        this.$message.error(res.msg?res.msg:"查询项目信息失败！")
      }

    },
    //登记项目
    handleAddProject(){
      this.$refs.addProjectForm.validate(valid => {
        if (!valid) {
          this.$message.error('存在错误内容，请完善信息！')
          return false
        } else {
          this.$confirm('确定添加该项目信息吗？', '提示',
              {
                'confirmButtonText': '确定',
                'cancelButtonText': '取消',
                'type': 'warning'
              }).then(async () => {
                let res=await AddProjectApi(this.projectMessage)
                if (res&&res.code===200){
                  this.$message.success("添加成功")
                  this.$parent.init()
                  this.close()
                }else {
                  this.$message.error(res.msg?res.msg:"添加失败")
                }
          }).catch((e)=>{
            if (e === 'cancel') {
              this.$message.info('取消添加')
            } else {
              this.$message.error('服务器错误，请联系管理员')
            }
          });
        }
      });
    },
    //修改项目
    handleEditProject(){
      this.$refs.addProjectForm.validate(valid => {
        if (!valid) {
          this.$message.error('存在错误内容，请完善信息！')
          return false
        } else {
          this.$confirm('确定修改该项目信息吗？', '提示',
              {
                'confirmButtonText': '确定',
                'cancelButtonText': '取消',
                'type': 'warning'
              }).then(async () => {
            let res=await UpdateProjectApi(this.projectMessage)
            if (res&&res.code===200){
              this.$message.success("修改成功")
              this.$parent.init()
              this.close()
            }else {
              this.$message.error(res.msg?res.msg:"添加失败")
            }
          }).catch((e)=>{
            if (e === 'cancel') {
              this.$message.info('取消添加')
            } else {
              this.$message.error('服务器错误，请联系管理员')
            }
          });
        }
      });
    },
    //关闭窗口
    close(){
      //取消表单项验证
      this.$nextTick(() => {
        this.$refs['addProjectForm'].clearValidate()
      })
      this.projectMessage={}

      store.commit('ProjectEdit/changeEditProjectSync',false)
      store.commit('ProjectEdit/changeEditProjectId',null)
    },
    //拦截关闭dialog
    handleCloseDialog () {
      this.$confirm('确定取消编辑项目信息吗？', '提示', {
        'confirmButtonText': '确定',
        'cancelButtonText': '取消',
        'type': 'info'
      }).then(() => {
        this.close()
      }).catch((e) => {
        if (e === 'cancel') {
        }
      })
    },
  },
  watch:{
    listenEditProjectId:{
      immediate:true,
      handler(val){
        if (val){
          this.init(val)
        }
      }
    }
  }
}
</script>
<style scoped lang="less">
.add-project{
  .add-project-dialog{
   border-radius: 10px;
    .add-project-card{
      .add-project__messageForm{
        width: 100%;
        padding:0 50px;
        .add-message{
          width: 200px;
        }
      }
      .add-project-editor{
        /deep/ .ql-container {
          overflow-y: scroll;
          height: 300px !important;
        }
      }
      .add-project-button{
        text-align: center;
        margin-top: 20px;
      }
    }
  }
  /deep/ .el-dialog {
    border-radius: 10px;
    margin-top: 80px !important;
  }
}
</style>
